<?php
// +----------------------------------------------------------------------------
// | Author: guanhanwen
// +----------------------------------------------------------------------------
/**
 +------------------------------------------------------------------------------
 * 社群
 +------------------------------------------------------------------------------
 * @since 2015-1-21
 +------------------------------------------------------------------------------
 */
namespace Home\Controller;
use Think\Controller;

class IndexController extends Controller {
	
	
	private $AppID = APP_ID;//微信AppID
	private $secret = SECRET;//微信secret
	private $host = '';//当前文件访问地址（一般需动态获取）
	
	
	/**
	 * @todo 初始化
	 * @since 2015-1-21
	 * @author guanhanwen
	 */
	public function _initialize(){
		$this->assign('host_url',$_SERVER['SERVER_NAME']);
		$this->assign('img_name','icon300.jpg');
		$this->assign('download_url',DOWNLOAD_URL);
		//如果不是ajax请求的话，就将当前地府赋值给成员属性$host
		if(!IS_AJAX){
			$this->host = 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
		}
		if(ACTION_NAME != 'myInvitation'){
			$share_data = array(
					'title'=> 'E-MBA云邀你进入社群时代',
					'desc' => '愈10万MBA/EMBA校友共同选择，36个区域社群，总有一个适合你^-^',
					'link' => SHARE_HOST.'/Index/index',
					'img_url' => SHARE_HOST.'/Public/Home/images/icon300.jpg'
			);
			$this->assign('share_data',$share_data);
		}
		
		$this->share();
		if(ACTION_NAME == 'index' || ACTION_NAME == 'myInvitation'){
			if(!session('fx')){
				//分享
				session('fx',time());
			}
		}else{
			if((ACTION_NAME != 'myInvitation' && !session('fx')) && ACTION_NAME != 'sessionNull'){
				session(null);
				header("Location:/Index/index");
			}
		}
// 		dump($share_data);die;
	}
	/**
	 * @todo 社群首页
	 * @since 2015-1-21
	 * @author guanhanwen
	 */
    public function index(){
// session(null);
		$this->display('index');
    }
    
    /**
	 * @todo 社群列表
	 * @since 2015-1-21
	 * @author guanhanwen
	 */
    public function communityList(){
// dump(session());die;
    	$user_id = (int)session('user_id');
    	$this->assign('user_id',$user_id);
    	$this->display('community_list');
    }
    
    /**
     * @todo 异步获取社群列表
     * @since 2015-1-23
     * @author guanhanwen
     */
    public function ajaxCommunityList(){
    	$user_id = (int)session('user_id');
    	$result = D('Guan')->getCommunityList($user_id);
    	if($result['result'] == 2){
    		$this->assign('error',$result['msg']);
    	}else{
    		$community_list = $result['data']['list'];
    		$this->assign('community_list',$community_list);
    	}
    	$this->display('ajax_community_list');
    }
    
    /**
     * @todo 注册
     * @since 2015-1-22
     * @author guanhanwen
     */
    public function reg(){
    	if(IS_AJAX){
    		$user_phone = I('post.user_phone');
    		$user_password = (string)I('post.user_password');
    		$user_name = I('post.user_name');
    		$school_id = (int)I('post.school_id');
    		$grade_id = (int)I('post.grade_id');
    		$verify_code = (int)I('post.verify_code');
    		$isMob="/^[0-9]{11}$/";
    		if(!preg_match($isMob,$user_phone)){
    			$this->ajaxReturn1('','请先输入正确的手机号码',1);
    		}
    		if(strlen($user_password) < 6 || strlen($user_password) > 18){
    			$this->ajaxReturn1('','密码长度在6-18个字符之间!',1);
    		}
    		import('Common.Org.Util.Encrypt', '', '.php');
    		$rule = new \EncryptCopy;
    		$user_password = $rule->encryptByKey($user_password, ENCRYPT_KEY);
    		if($user_name == ''){
    			$this->ajaxReturn1('','请输入姓名!',1);
    		}
    		if($school_id == 0 || $grade_id == 0){
    			$this->ajaxReturn1('','请正确选择学校和年级后提交!',1);
    		}
    		//判断验证码是否正确
    		if($user_phone != session('veri_phone') || $verify_code != session('veri_code')){
    			if($verify_code != DEFAULT_CODE){
    				$this->ajaxReturn1('','验证码错误',1);
    			}
    		}
    		//写入平台
    		$data['user_phone'] = $user_phone;
    		$data['user_password'] = $user_password;
    		$data['user_name'] = $user_name;
    		$data['school_id'] = $school_id;
    		$data['grade_id'] = $grade_id;
    		$result = D('Guan')->inputUserInfo($data);
    		if($result['result'] != 0){
    			$this->ajaxReturn1('','平台写入失败',1);
    		}
    		if($result['status'] == 1){
    			//新用户发短信
    			$notice = "&content=".rawurlencode("恭喜你！成为E-MBA云用户，请访问 http://embayun.com/reg/done 下载客户端。【E-MBA云】")."&ext=&stime=&rrid=&msgfmt=";
//     			$this->sendSmsRealOld($user_phone,$notice);
    			$template = 'MB-2015020311';
    			$this->sendSmsReal($user_phone,'',$template);
    		}
    		if($result['status'] == 2){
    			$this->ajaxReturn1('','手机号码已存在',1);
    		}
    		session('user_id',null);
    		session('user_phone',null);
    		session('user_name',null);
    		session('join_community_arr',null);
    		session('user_id',$result['user_id']);
    		session('user_phone',$user_phone);
    		session('user_name',$user_name);
    		$this->ajaxReturn1('','注册成功',0);
    	}else{
	    	//判断本地的code跟地址传过来的是否一致，不一致的话踢回联合发起人页
	    	$emba_code = I('get.code');
	    	$father_id = (int)I('get.id');
	    	//按拼音排序后的学校列表
	    	$school = $this->schoolSort();
	    	$school = array_merge($school);
	    	$this->assign('school_list',$school);
	    	$this->display();
    	}
    }
    
    /**
	 * @todo 登录
	 * @since 2015-1-21
	 * @author guanhanwen
	 */
    public function login(){
    	if($this->isAjax()){
    		$user_phone = I('post.user_phone');
    		$user_password = I('post.user_password');//'123456';
    		$isMob="/^[0-9]{11}$/";
    		if(!preg_match($isMob,$user_phone)){
    			$this->ajaxReturn1('','请先输入正确的手机号码',1);
    		}
    		if(strlen($user_password) < 6 || strlen($user_password) > 18){
    			$this->ajaxReturn1('','密码长度在6-18个字符之间!',1);
    		}
    		$result = D('Guan')->loginUserV2($user_phone,$user_password);
    		if($result['result'] != 0){
    			if($result['msg'] != ''){
    				$msg = $result['msg'];
    			}else{
    				$msg = '登录失败';
    			}
    			$this->ajaxReturn1('',$msg,1);
    		}
    		$user_info = $result['data'];
// dump($user_info);die;
    		//使用用户名、密码和状态的方式进行认证
    		if((int)$user_info['_id'] > 0){
    			session('user_id',null);
    			session('user_phone',null);
    			session('user_name',null);
    			session('join_community_arr',null);
    			session('user_id',$user_info['_id']);
    			session('user_phone',$user_info['user_login']);
    			session('user_name',$user_info['user_name']);
// dump(session());die;
    			$this->ajaxReturn1($user_info,"登录成功",0);
    		}else {
    			$this->ajaxReturn1('',"登录账号或密码错误",1);
    		}
    	}else{
//     		dump(session());
    		session('user_id',null);
    		session('user_phone',null);
    		session('user_name',null);
    		session('join_community_arr',null);
    		$this->display('login');
    	}
    }
    
    /**
     * @todo 异步请求加入社群的方法
     * @since 2015-1-21
     * @author guanhanwen
     */
    public function joinCommunity(){
    	if(IS_AJAX){
    		$user_id = session('user_id');
// echo $user_id;die;
    		$community_id = (int)I('post.community_id');
    		$invite_id = (int)I('post.invite_id');
    		if((int)$user_id <= 0 || $community_id <= 0){
    			$this->ajaxReturn1('',"参数错误",1);
    		}
    		if($invite_id == $user_id){
    			$this->ajaxReturn1($invite_id,'您已是此群成员，现进入到邀请函页。',1);
    		}
    		$result = D('Guan')->joinCommunity($user_id,$community_id,$invite_id);
// dump($result);die;
    		if($result['result'] != 2 && $result['result'] != 0){
    			$this->ajaxReturn1('',"操作失败",1);
    		}elseif($result['result'] == 2){
    			//确定是什么类型的错误。决定是跳转重复添加页还是直接报error
    			$msg_arr = explode(':', $result['msg']);
    			$community_arr = explode(',', $msg_arr[1]);
    			foreach($community_arr as $key=>$val){
    				$community_arr[$key] = explode('@', $val);
    			}
    			
    			//$msg_arr[0]
    			//1:已经加入了该群
    			// 2:每个用户最多加入2个群
    			// 3:在WAP页中只能加入一个群
    			if($msg_arr[0] == '1'){
    				$this->ajaxReturn1(1,$user_id,0);
    			}else{
    				session('join_community_arr',null);
    				session('join_community_arr',$community_arr);
// dump(session('join_community_arr'));die;
    				$this->ajaxReturn1(2,"超过加入社群限制",0);
    				//header("Location:/Index/only");
    			}
    		}else{
// dump($result);die;
    			$msg_arr = explode(':', $result['msg']);
    			$community_arr = explode(',', $msg_arr[0]);
    			foreach($community_arr as $key=>$val){
    				$community_arr[$key] = explode('@', $val);
    			}
    			//成功跳入邀请函页面
    			$this->ajaxReturn1(3,$community_arr[0][1],0);
    		}
    	}else{
    		$this->display('get_invitation');
    	}
		
    }
    
    /**
     * @todo 添加社群后异步向用户客户端推送一个消息
     * @since 2015-2-2
     * @author guanhanwen
     */
    public function publicPushNotice(){
    	if(IS_AJAX){
    		$user_id = session('user_id');
    		$title = '推送通知';
    		$info = '推送通知';
    		$action = '10';
    		$result = D('Guan')->publicPushNotice($user_id,$title,$info,$action,array());
    		if($result['result'] == '0' && $result != null){
    			$this->ajaxReturn1('',"操作成功",0);
    		}else{
    			$this->ajaxReturn1('',"操作失败",1);
    		}
    	}else{
    		header("Location:/Index/index");
    	}
    }
    
    /**
     * @todo 找回密码
     * @since 2015-2-3
     * @author guanhanwen
     */
    public function findPassword(){
    	if(IS_AJAX){
    		$user_phone = I('post.user_phone');
    		$user_password = (string)I('post.user_password');
    		$user_password_r = (string)I('post.user_password_r');
    		$verify_code = (int)I('post.verify_code');
    		$isMob="/^[0-9]{11}$/";
    		if(!preg_match($isMob,$user_phone)){
    			$this->ajaxReturn1('','请先输入正确的手机号码',1);
    		}
    		if(strlen($user_password) < 6 || strlen($user_password) > 18){
    			$this->ajaxReturn1('','密码长度在6-18个字符之间!',1);
    		}
    		if($user_password != $user_password_r){
    			$this->ajaxReturn1('','请保证两次密码填写一致!',1);
    		}
    		//判断验证码是否正确
    		if($user_phone != session('veri_phone') || $verify_code != session('veri_code')){
    			if($verify_code != DEFAULT_CODE){
    				$this->ajaxReturn1('','验证码错误',1);
    			}
    		}
    		//请求接口修改密码
    		$result = D('Guan')->sendPasswordV3($user_phone,$user_password);
    		if($result['result'] == 0){
    			$this->ajaxReturn1('','找回密码成功',0);
    		}else{
    			$this->ajaxReturn1('',$result['msg'],1);
    		}
    	}else{
    		$this->display('find_password');
    	}
    }
    

    /**
     * @todo 获取我的邀请函
     * @since 2015-1-21
     * @author guanhanwen
     */
	public function getInvitation(){
		if(!session('user_id')){
			header("Location:/Index/communityList");
		}
		$this->assign('user_id',session('user_id'));
		$this->display('get_invitation');
	}

	/**
	 * @todo 我的邀请函
	 * @since 2015-1-21
	 * @author guanhanwen
	 */
	public function myInvitation(){
		$community_id = (int)I('get.community_id');
		$invite_id = (int)I('get.invite_id');
		$para1 = I('get.para1');
// 		$para1 = 'NIPpL3iV-h1e2EgBJTSGmw==';
		//如果para1值存在说明是客户端请求过来的。执行自动登录
		if($para1 !='' || $para1 != null){
			import('Common.Org.Util.Aes', '', '.php');
			$this->aes1 = new \Aes();
			$app_user_id = (int)json_decode(urldecode($this->aes1->siyuan_aes_decode(str_replace("-","/",str_replace(" ","+",$para1)))),TRUE);
		}else{
			session('app_para1',null);
		}
		if($community_id <= 0 || $invite_id <= 0){
			$this->error('请勿非法访问该活动');
		}
		$result = D('Guan')->invitationInfo($community_id,$invite_id);
		if($result['result'] == 0){
			$inviation_info['community_id'] = $result['data']['community']['community_id'];
			$inviation_info['community_name'] = $result['data']['community']['community_name'];
			$inviation_info['user_id'] = $result['data']['user']['user_id'];
			$inviation_info['user_name'] = $result['data']['user']['user_name'];
			$school_name = $result['data']['user']['school_short_name'];
			if($school_name != ''){
				$shcool_arr = explode('/', $result['data']['user']['school_short_name']);
				$school_name = $shcool_arr[0];
			}
			if($app_user_id > 0 && $invite_id == $app_user_id){
				$this->assign('app_para1',1);
				session('app_para1',1);
				session('user_id',$result['data']['user']['user_id']);
				session('user_name',$result['data']['user']['user_name']);
			}
			$inviation_info['school_name'] = $school_name;
			$this->assign('inviation_info',$inviation_info);
		}else{
			header("Location:/Index/only");
		}
		//如果session('user_id)不等于invite_id,显示邀请人的模板，否则显示我的邀请函模板
		if($invite_id == session('user_id')){
			$tpl = 'my_invitation';
			$this->assign('img_name','icon300_2.jpg');
			$title = "我是".$inviation_info['user_name']."，已加入".$inviation_info['community_name'].",邀你一起进入社群时代";
			$this->assign('title',$title);
				
			$share_data = array(
					'title'=> $title,
					'desc' => '愈10万MBA/EMBA校友共同选择，36个区域社群，总有一个适合你^-^',
					'link' => $this->host,
					'img_url' => SHARE_HOST.'/Public/Home/images/icon300_2.jpg'
			);
			$this->assign('share_data',$share_data);
		}else{
			$tpl = 'join_now';
			$title = "我是".$inviation_info['user_name']."，已加入".$inviation_info['community_name'].",邀你一起进入社群时代";
			$this->assign('title',$title);
			
			$share_data = array(
					'title'=> $title,
					'desc' => '愈10万MBA/EMBA校友共同选择，36个区域社群，总有一个适合你^-^',
					'link' => $this->host,
					'img_url' => SHARE_HOST.'/Public/Home/images/icon300_2.jpg'
			);

			$this->assign('share_data',$share_data);
		}
// 		dump($tpl);die;
		$this->display($tpl);
	}
	
	/**
	 * @todo 只能加入一个社群提示页面
	 * @since 2015-1-21
	 * @author guanhanwen
	 */
	public function only(){
// dump(session());die;
		$user_id = session('user_id');
		$community_arr = session('join_community_arr');
		if(!$user_id || empty($community_arr)){
			header("Location:/Index/index");
			//$this->error('请勿非法访问EMBA云活动','http://'.$_SERVER['HTTP_HOST'].'/Index/communityList');
		}
		$this->assign('user_id',$user_id);
		$this->display();
	}
	
	/**
	 * @todo 邀请列表
	 * @since 2015-2-5
	 * @author guanhanwen
	 */
	public function invitedList(){
		$this->display('invited_list');
	}
	
	public function ajaxInvitedList(){
		$community_id = I('get.community_id');
		$user_id = I('get.user_id');
		$list_last_id = I('get.list_last_id');
		$result = D('Guan')->getUserInviteList($community_id,$user_id,$list_last_id);
// echo "<br />&nbsp;<br />&nbsp;<br />&nbsp;<br />&nbsp;";
// dump($result);die;
		$certified = 0;
		$validate_count = 0;
		$effict = 0;
		$count = 0;
		if($result['result'] == 2 || $result['result'] == 1){
			$this->assign('more',0);
			$this->assign('notice',$result['msg']);
		}elseif($result['result'] == 0){
			$this->assign('more',1);
			$hand = $result['data'];

			$count = $hand['count'];
// dump($hand);die;
			//已认证
			$validate_count = (int)$hand['validate_count'];
			$list = $hand['list'];
			$row_number = count($list);
			//用于计算是否为最后一页
			$this->assign('row_number',$row_number);
			$last_id = $list[$row_number-1]['id'];

			//已认证
			$this->assign('last_id',$last_id);
			$this->assign('list',$list);
		}else{
			$this->assign('notice',$result['msg']);
		}
		$this->assign('validate_count',$validate_count);
		$this->assign('count',$count);
// dump($list);die;
		$this->display('ajax_invited_list');
	}
	
	/**
	 * @todo 获取学校列表并按字母排序
	 * @since 2015-1-21
	 * @author guanhanwen
	 */
    public function schoolSort(){
    	$school_list = D('Guan')->getSchoolList();
    	$school = $school_list['data'];
    	foreach($school as $key=>$val){
    		$school[$key]['pinyin'] = $this->Pinyin($val['school_name'],'UTF-8');
			//重（zhong）庆,替换为重（chong）庆
			if(substr($val['school_name'], 0,3) == '重'){
				$school[$key]['pinyin'] = preg_replace("/^zhong/", "chong", $school[$key]['pinyin']);
			}
			if(substr($val['school_name'], 0,3) == '暨'){
				$school[$key]['pinyin'] = 'ji'.$school[$key]['pinyin'];
			}
			$school[$key]['first'] = strtoupper(msubstr($school[$key]['pinyin'], 0,1));
    	}
    	$school = $this->array_sort($school,'pinyin');
    	return $school;
    }
    
    /**
	 * @todo 获取学届
	 * @since 2015-1-21
	 * @author guanhanwen
	 */
    public function getGrade(){
    	$school_id = (int)I('get.school_id');
    	$grade_id = (int)I('get.grade_id');
    	if($school_id == 0){
    		$this->error('参数错误');
    	}
    	if($grade_id > 0){
    		$this->assign('grade_id',$grade_id);
    	}
    	$result = D('Guan')->getGradeList($school_id);
    	if($result['result'] != 0 ){
    		$this->error('数据请求shibai错误');
    	}
    	//     	 dump($result);die;
    	$this->assign('grade_list',$result['msg']);
    	$this->display('grade_list');
    	 
    }

    /**
     * @todo 按字母排序
     * @since 2015-1-21
     * @author guanhanwen
     */
    function Pinyin($_String, $_Code='UTF8'){ //GBK页面可改为gb2312，其他随意填写为UTF8
    	$_DataKey = "a|ai|an|ang|ao|ba|bai|ban|bang|bao|bei|ben|beng|bi|bian|biao|bie|bin|bing|bo|bu|ca|cai|can|cang|cao|ce|ceng|cha".
    			"|chai|chan|chang|chao|che|chen|cheng|chi|chong|chou|chu|chuai|chuan|chuang|chui|chun|chuo|ci|cong|cou|cu|".
    			"cuan|cui|cun|cuo|da|dai|dan|dang|dao|de|deng|di|dian|diao|die|ding|diu|dong|dou|du|duan|dui|dun|duo|e|en|er".
    			"|fa|fan|fang|fei|fen|feng|fo|fou|fu|ga|gai|gan|gang|gao|ge|gei|gen|geng|gong|gou|gu|gua|guai|guan|guang|gui".
    			"|gun|guo|ha|hai|han|hang|hao|he|hei|hen|heng|hong|hou|hu|hua|huai|huan|huang|hui|hun|huo|ji|jia|jian|jiang".
    			"|jiao|jie|jin|jing|jiong|jiu|ju|juan|jue|jun|ka|kai|kan|kang|kao|ke|ken|keng|kong|kou|ku|kua|kuai|kuan|kuang".
    			"|kui|kun|kuo|la|lai|lan|lang|lao|le|lei|leng|li|lia|lian|liang|liao|lie|lin|ling|liu|long|lou|lu|lv|luan|lue".
    			"|lun|luo|ma|mai|man|mang|mao|me|mei|men|meng|mi|mian|miao|mie|min|ming|miu|mo|mou|mu|na|nai|nan|nang|nao|ne".
    			"|nei|nen|neng|ni|nian|niang|niao|nie|nin|ning|niu|nong|nu|nv|nuan|nue|nuo|o|ou|pa|pai|pan|pang|pao|pei|pen".
    			"|peng|pi|pian|piao|pie|pin|ping|po|pu|qi|qia|qian|qiang|qiao|qie|qin|qing|qiong|qiu|qu|quan|que|qun|ran|rang".
    			"|rao|re|ren|reng|ri|rong|rou|ru|ruan|rui|run|ruo|sa|sai|san|sang|sao|se|sen|seng|sha|shai|shan|shang|shao|".
    			"she|shen|sheng|shi|shou|shu|shua|shuai|shuan|shuang|shui|shun|shuo|si|song|sou|su|suan|sui|sun|suo|ta|tai|".
    			"tan|tang|tao|te|teng|ti|tian|tiao|tie|ting|tong|tou|tu|tuan|tui|tun|tuo|wa|wai|wan|wang|wei|wen|weng|wo|wu".
    			"|xi|xia|xian|xiang|xiao|xie|xin|xing|xiong|xiu|xu|xuan|xue|xun|ya|yan|yang|yao|ye|yi|yin|ying|yo|yong|you".
    			"|yu|yuan|yue|yun|za|zai|zan|zang|zao|ze|zei|zen|zeng|zha|zhai|zhan|zhang|zhao|zhe|zhen|zheng|zhi|zhong|".
    			"zhou|zhu|zhua|zhuai|zhuan|zhuang|zhui|zhun|zhuo|zi|zong|zou|zu|zuan|zui|zun|zuo";
    	$_DataValue = "-20319|-20317|-20304|-20295|-20292|-20283|-20265|-20257|-20242|-20230|-20051|-20036|-20032|-20026|-20002|-19990".
    			"|-19986|-19982|-19976|-19805|-19784|-19775|-19774|-19763|-19756|-19751|-19746|-19741|-19739|-19728|-19725".
    			"|-19715|-19540|-19531|-19525|-19515|-19500|-19484|-19479|-19467|-19289|-19288|-19281|-19275|-19270|-19263".
    			"|-19261|-19249|-19243|-19242|-19238|-19235|-19227|-19224|-19218|-19212|-19038|-19023|-19018|-19006|-19003".
    			"|-18996|-18977|-18961|-18952|-18783|-18774|-18773|-18763|-18756|-18741|-18735|-18731|-18722|-18710|-18697".
    			"|-18696|-18526|-18518|-18501|-18490|-18478|-18463|-18448|-18447|-18446|-18239|-18237|-18231|-18220|-18211".
    			"|-18201|-18184|-18183|-18181|-18012|-17997|-17988|-17970|-17964|-17961|-17950|-17947|-17931|-17928|-17922".
    			"|-17759|-17752|-17733|-17730|-17721|-17703|-17701|-17697|-17692|-17683|-17676|-17496|-17487|-17482|-17468".
    			"|-17454|-17433|-17427|-17417|-17202|-17185|-16983|-16970|-16942|-16915|-16733|-16708|-16706|-16689|-16664".
    			"|-16657|-16647|-16474|-16470|-16465|-16459|-16452|-16448|-16433|-16429|-16427|-16423|-16419|-16412|-16407".
    			"|-16403|-16401|-16393|-16220|-16216|-16212|-16205|-16202|-16187|-16180|-16171|-16169|-16158|-16155|-15959".
    			"|-15958|-15944|-15933|-15920|-15915|-15903|-15889|-15878|-15707|-15701|-15681|-15667|-15661|-15659|-15652".
    			"|-15640|-15631|-15625|-15454|-15448|-15436|-15435|-15419|-15416|-15408|-15394|-15385|-15377|-15375|-15369".
    			"|-15363|-15362|-15183|-15180|-15165|-15158|-15153|-15150|-15149|-15144|-15143|-15141|-15140|-15139|-15128".
    			"|-15121|-15119|-15117|-15110|-15109|-14941|-14937|-14933|-14930|-14929|-14928|-14926|-14922|-14921|-14914".
    			"|-14908|-14902|-14894|-14889|-14882|-14873|-14871|-14857|-14678|-14674|-14670|-14668|-14663|-14654|-14645".
    			"|-14630|-14594|-14429|-14407|-14399|-14384|-14379|-14368|-14355|-14353|-14345|-14170|-14159|-14151|-14149".
    			"|-14145|-14140|-14137|-14135|-14125|-14123|-14122|-14112|-14109|-14099|-14097|-14094|-14092|-14090|-14087".
    			"|-14083|-13917|-13914|-13910|-13907|-13906|-13905|-13896|-13894|-13878|-13870|-13859|-13847|-13831|-13658".
    			"|-13611|-13601|-13406|-13404|-13400|-13398|-13395|-13391|-13387|-13383|-13367|-13359|-13356|-13343|-13340".
    			"|-13329|-13326|-13318|-13147|-13138|-13120|-13107|-13096|-13095|-13091|-13076|-13068|-13063|-13060|-12888".
    			"|-12875|-12871|-12860|-12858|-12852|-12849|-12838|-12831|-12829|-12812|-12802|-12607|-12597|-12594|-12585".
    			"|-12556|-12359|-12346|-12320|-12300|-12120|-12099|-12089|-12074|-12067|-12058|-12039|-11867|-11861|-11847".
    			"|-11831|-11798|-11781|-11604|-11589|-11536|-11358|-11340|-11339|-11324|-11303|-11097|-11077|-11067|-11055".
    			"|-11052|-11045|-11041|-11038|-11024|-11020|-11019|-11018|-11014|-10838|-10832|-10815|-10800|-10790|-10780".
    			"|-10764|-10587|-10544|-10533|-10519|-10331|-10329|-10328|-10322|-10315|-10309|-10307|-10296|-10281|-10274".
    			"|-10270|-10262|-10260|-10256|-10254";
    	$_TDataKey   = explode('|', $_DataKey);
    	$_TDataValue = explode('|', $_DataValue);
    	$_Data = array_combine($_TDataKey, $_TDataValue);
    	arsort($_Data);
    	reset($_Data);
    	if($_Code!= 'gb2312') $_String = $this->_U2_Utf8_Gb($_String);
    	$_Res = '';
    	for($i=0; $i<strlen($_String); $i++) {
    		$_P = ord(substr($_String, $i, 1));
    		if($_P>160) {
    			$_Q = ord(substr($_String, ++$i, 1)); $_P = $_P*256 + $_Q - 65536;
    		}
    		$_Res .= $this->_Pinyin($_P, $_Data);
    	}
    	return preg_replace("/[^a-z0-9]*/", '', $_Res);
    }
    
    /**
     * @todo 按字母排序
     * @since 2015-1-21
     * @author guanhanwen
     */
    function _Pinyin($_Num, $_Data){
    	if($_Num>0 && $_Num<160 ){
    		return chr($_Num);
    	}elseif($_Num<-20319 || $_Num>-10247){
    		return '';
    	}else{
    		foreach($_Data as $k=>$v){ if($v<=$_Num) break; }
    		return $k;
    	}
    }
    
    /**
     * @todo 按字母排序
     * @since 2015-1-21
     * @author guanhanwen
     */
    function _U2_Utf8_Gb($_C){
    	$_String = '';
    	if($_C < 0x80){
    		$_String .= $_C;
    	}elseif($_C < 0x800) {
    		$_String .= chr(0xC0 | $_C>>6);
    		$_String .= chr(0x80 | $_C & 0x3F);
    	}elseif($_C < 0x10000){
    		$_String .= chr(0xE0 | $_C>>12);
    		$_String .= chr(0x80 | $_C>>6 & 0x3F);
    		$_String .= chr(0x80 | $_C & 0x3F);
    	}elseif($_C < 0x200000) {
    		$_String .= chr(0xF0 | $_C>>18);
    		$_String .= chr(0x80 | $_C>>12 & 0x3F);
    		$_String .= chr(0x80 | $_C>>6 & 0x3F);
    		$_String .= chr(0x80 | $_C & 0x3F);
    	}
    	return iconv('UTF-8', 'GB2312', $_String);
    }
    
    /**
     *
     * @todo 二维数组按某个字段派讯
     * @param unknown $arr
     *        	需要排序的数组
     * @param unknown $keys
     *        	需要排序的字段名
     * @param string $type
     *        	排序的方式 正序或倒叙
     * @return multitype:unknown
     */
    function array_sort($arr, $keys, $type = 'asc') {
    	$keysvalue = $new_array = array ();
    	foreach ( $arr as $k => $v ) {
    		$keysvalue [$k] = $v [$keys];
    	}
    	if ($type == 'asc') {
    		asort ( $keysvalue );
    	} else {
    		arsort ( $keysvalue );
    	}
    	reset ( $keysvalue );
    	foreach ( $keysvalue as $k => $v ) {
    		$new_array [$k] = $arr [$k];
    	}
    	return $new_array;
    }
    
    /**
     * @todo	参加活动获取验证码
     */
    public function getVerify(){
    	if(IS_AJAX){
    		$phone = I('post.user_phone');
    		//type=1 注册，2找回密码
    		$type = I('post.type');
    		//先判断手机号和session中的手机号不相同或者没有session
    		if(session('veri_phone') != $phone ||(session('veri_phone') == '' || session('veri_phone') == null) || (session('veri_code') == '' || session('veri_code') == null)){
				$code = $this->getCode();
				session('veri_code',$code);
				session('veri_phone',$phone);
				session('veri_code_time',time());
			}else{
				//判断一分钟以内不能重复发送验证码
				$cha = time() - session('veri_code_time');
				if($cha < 60){
					$this->ajaxReturn1('','每分钟只可以获取一次验证码',1);
				}
				$code = session('veri_code');
			}
			if($type == 1){
				$result = D('Guan')->zcIsPhone($phone);
				if($result['result'] == '0'){
					$this->ajaxReturn1('','该手机号码已被注册！',1);
				}
			}
			//每次发送前更新记录的发送时间
			session('veri_code_time',time());
    		$notice = "&content=".rawurlencode("您的验证码是：".$code."。请不要把验证码泄露给其他人。【E-MBA云】")."&ext=&stime=&rrid=&msgfmt=";
//     		$this->sendSmsRealOld($phone,$notice);
    		$template = "MB-2015012956";
    		$this->sendSmsReal($phone,$code,$template);
    		$this->ajaxReturn1('','验证码已发送至您的手机中',0);
    	}else{
    		$this->error('请不要非法访问');
    	}
    }

    
    /**
     * @todo 获取随机数
     * @since 2015-1-21
     * @author guanhanwen
     */
    public function getCode(){
    	srand((double)microtime()*1000000);//create a random number feed.
    	$ychar='1,2,3,4,5,6,7,8,9';
    	$list=explode(',',$ychar);
    
    	for($i=0;$i<4;$i++){
    		$randnum=rand(0,8); // 10+26;
    		$authnum.=$list[$randnum];
    	}
    	return $authnum;
    }
    
    /**
     * @todo 发送短信接口
     * @since 2015-1-21
     * @author fangnengwan
     */
    public function sendSmsRealOld($mobile_phone_str,$content){
    	$post_data = "&mobile=".$mobile_phone_str.$content;//"&content=".rawurlencode("您的验证码是：".$content."。请不要把验证码泄露给其他人。【E-MBA云】")."&ext=&stime=&rrid=&msgfmt="
    	$call_back = $this->curl_post($post_data,"http://sdk2.entinfo.cn:8061/mdsmssend.ashx?sn=SDK-BBX-010-21016&pwd=E77BC0436C98B9CE19B0E0D22395CBC9");
    	return $call_back;
    }
    
    /**
     * @todo 新发送短信方法
     */
    public function sendSmsReal($phone,$code,$template){

    	$Client	= new \Org\Util\HttpClient("mssms.cn:8000");
    	$url = "http://mssms.cn:8000/msm/sdk/http/sendsms.jsp";
    	$params = array('username'=>"XFTB702012",'scode'=>"445686",'mobile'=>$phone,'content'=>"@1@=".$code,'tempid'=>$template);
    	$pageContents = $Client::quickPost($url, $params);
// dump($pageContents);die;
    	return $pageContents;
    }
    
    
    /**
     * @todo	curl_post
     */
    public function curl_post($curlPost,$url){
    	$curl = curl_init();
    	curl_setopt($curl, CURLOPT_URL, $url);
    	curl_setopt($curl, CURLOPT_HEADER, false);
    	curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    	curl_setopt($curl, CURLOPT_NOBODY, true);
    	curl_setopt($curl, CURLOPT_POST, true);
    	curl_setopt($curl, CURLOPT_POSTFIELDS, $curlPost);
    	$return_str = curl_exec($curl);
    	$post_result = rawurldecode($curlPost);
    	$this->writeErrLog("CURL--POST接口调用成功,'--'.Post:$post_result\n" , APP_ROOT .'/#Logs/Reg/'.date('Y-m-d').'.txt');
    	curl_close($curl);
    	return $return_str;
    }
    
    /**
     * @todo 写错误日志
     */
    public function writeErrLog($errorMes, $file_name = '') {
    	if(empty($errorMes)) {
    		return false;
    	}
    	//目录不存在就创建
    	if (!file_exists (dirname($file_name))) {
    		if (!@mkdir (dirname($file_name), 0777)) {
    			die($file_name.'目录创建失败！');
    		}
    	}
    	$msg = date('Y-m-d H:i:s').' >>> '.$errorMes.'\r\n';
    	file_put_contents($file_name,$msg,FILE_APPEND);
    }
    
    //session清理
    public function sessionNull(){
    	session(null);
    	header("Content-type: text/html; charset=utf-8"); 
    	echo "SESSION清理成功!";
    }

    public function share(){
    	//签名：将jsapi_ticket、noncestr、timestamp、分享的url按字母顺序连接起来，进行sha1加密，做为签名。
    	$timestamp=time();//当前时间戳。
    	$nonceStr = $this->getRandChar(10);//任意字符串。
    	$ticket = $this->wx_get_jsapi_ticket();
// dump($this->host);die;
    	$ori = sprintf("jsapi_ticket=%s&noncestr=%s&timestamp=%s&url=%s",$ticket, $nonceStr, $timestamp,$this->host);
    	$sha1 = sha1($ori);//对str串做sha1加密，
    	$this->assign('AppID',$this->AppID);//AppID
    	$this->assign('timestamp',$timestamp);//时间戳
    	$this->assign('nonceStr',$nonceStr);//任意字符串
    	$this->assign('sha1',$sha1);//签名
//     	$this->display('share');
    }
    
    //获取token
    public function wx_get_token() {
    	$token = S('access_token');
    	// 通过此接口返回的token的有效期目前为2小时。令牌失效后，JS-SDK也就不能用了。
    	// 因此，这里将token值缓存起来（小于2小时）。缓存失效后，再从接口获取新的token
    	// 这样就可以避免token失效（当然如必要，也可以写入数据库中）
    	if (!$token) {
    		$res = file_get_contents('https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$this->AppID.'&secret='.$this->secret
    		);
    		// 不能频繁的访问https://api.weixin.qq.com/cgi-bin/token，每日有次数限制（一般为2000次）
    		$res = json_decode($res, true);
    		$token = $res['access_token'];
    		S('access_token', $token, 3600);//缓存1小时
    	}
    	return $token;
    	//注意：返回的access_token长度至少要留够512字节
    }
    
    
    //获取jsapi的ticket。
    //jsapi_ticket是公众号用于调用微信JS接口的临时票据，jsapi_ticket有效期7200秒
    public function wx_get_jsapi_ticket(){
    	$ticket = "";
    	do{
    		$ticket = S('wx_ticket');
    		if (!empty($ticket)) {
    			break;
    		}
    		$token = S('access_token');
    		if (empty($token)){
    			$this->wx_get_token();//获取token
    		}
    		$token = S('access_token');
    		if (empty($token)) {
    			break;
    		}
    		$url2 = sprintf("https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=%s&type=jsapi",
    				$token);
    		$res = file_get_contents($url2);
    		$res = json_decode($res, true);
    		$ticket = $res['ticket'];
    		// 注意：这里需要将获取到的ticket缓存起来（或写到数据库中）
    		// ticket和token一样，不能频繁的访问接口来获取，在每次获取后，我们把它保存起来。
    		S('wx_ticket', $ticket, 3600);
    	}while(0);
    	return $ticket;
    }
    
    //生成随机字符串
    public function getRandChar($length){
    	$str = "";
    	$strPol = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz";
    	$max = strlen($strPol)-1;
    
    	for($i=0;$i<$length;$i++){
    		$str.=$strPol[rand(0,$max)];//rand($min,$max)生成介于min和max两个数之间的一个随机整数
    	}
    	return $str;
    }
}


 
 